package com.keke.beauty.sys.weixin;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import com.github.sd4324530.fastweixin.api.enums.ResultType;
import com.github.sd4324530.fastweixin.api.response.BaseResponse;
import com.github.sd4324530.fastweixin.util.NetWorkCenter;
import com.keke.beauty.sys.weixin.wechat.WechatAccountConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.keke.beauty.sys.wxUser.entity.TabWxUser;
import com.keke.beauty.sys.wxUser.service.TabWxUserService;
import com.keke.beauty.utils.pojo.Result;
import com.keke.beauty.utils.tools.ResultUtil;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    final static String base_url = "https://api.weixin.qq.com/sns/";

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private TabWxUserService wxUserService;

    @Autowired
    private WechatAccountConfig wechatAccountConfig;

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl, String referralsOpenId, HttpServletRequest request) {
        if (!StringUtils.isEmpty(referralsOpenId)) {
            returnUrl += "&referralsOpenId=" + referralsOpenId;
        }
        System.out.println(returnUrl);
        String basePath = request.getScheme() + "://" + request.getServerName();
        System.out.println(basePath + "/wechat/userInfo");
        @SuppressWarnings("deprecation")
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(basePath + "/wechat/userInfo", WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
//            String accessToken = wxMpOAuth2AccessToken.getAccessToken();
            // 获取用户微信账户信息
//            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMpOAuth2AccessToken.getOpenId());
            WxMpUser wxMpUser = getWxUserInfo(wxMpOAuth2AccessToken.getAccessToken(),wxMpOAuth2AccessToken.getOpenId());
            TabWxUser wxUser = wxUserService.findByPrimaryKey(wxMpUser.getOpenId());
            if (StringUtils.isEmpty(wxUser)) {
                wxMpUser.setNickname(wxMpUser.getNickname().replaceAll("[\\x{10000}-\\x{10FFFF}]",""));
                wxUserService.insert(wxMpUser);
            }
            System.out.println(wxMpUser.toString());
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【微信网页授权】openId={}", openId);
        return "redirect:" + returnUrl + "&openid=" + openId;
    }


    @PostMapping("/getSignature")
    @ResponseBody
    public Result getSignature(String webUrl, HttpServletRequest request) {
        try {
            System.out.println("webUrl = [" + webUrl + "]");
            WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(webUrl);
            return ResultUtil.success(jsapiSignature);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @MethodName: getWxUserInfo
     * @Describe: 获取微信用户
     * @Author: HL
     * @Date: 2019/3/6 23:28
     */
    public static WxMpUser getWxUserInfo(String accessToken, String openId){
        WxMpUser wxUserInfo = null;
        String getUserUrl = base_url+"userinfo?access_token="+ accessToken +"&openid="+ openId +"&lang=zh_CN";
        BaseResponse rr = NetWorkCenter.get(getUserUrl);
        if(isSuccess(rr.getErrcode())){
            System.out.println(rr.getErrmsg());
            wxUserInfo = WxMpUser.fromJson(rr.getErrmsg());
        }
        return wxUserInfo;

    }

    private static boolean isSuccess(String errCode) {
        return ResultType.SUCCESS.getCode().toString().equals(errCode);
    }

}
